package com.example.library.controller;

import com.example.library.entity.User;
import com.example.library.service.UserService;
import com.example.library.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> body) {
        String username = body.get("username");
        String password = body.get("password");
        Map<String, Object> res = new HashMap<>();
        User user = userService.findByUsername(username).orElse(null);
        if (user == null || !userService.checkPassword(password, user.getPassword())) {
            res.put("success", false);
            res.put("msg", "用户名或密码错误");
            return res;
        }
        String token = jwtUtil.generateToken(user.getUsername(), user.getRole());
        res.put("success", true);
        res.put("token", token);
        res.put("role", user.getRole());
        res.put("name", user.getName());
        return res;
    }
}
